package io.itit.ecp.admin.provide.action.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import icu.mhb.mybatisplus.plugln.core.JoinLambdaWrapper;
import icu.mhb.mybatisplus.plugln.extend.Joins;
import io.itit.ecp.admin.common.enums.IMeterDeviceEnums;
import io.itit.ecp.admin.provide.action.req.CarbonEmissionDataQueryReq;
import io.itit.ecp.admin.provide.action.resp.CarbonEmissionDataResp;
import io.itit.ecp.admin.provide.helper.SceneHelper;
import io.itit.ecp.admin.server.entity.*;
import io.itit.ecp.admin.server.entity.extend.EnergyDataExtEntity;
import io.itit.ecp.admin.server.service.IEnergyDataService;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.IExport;
import io.itit.grass.common.provide.action.validation.IQueryPage;
import io.itit.grass.common.provide.action.validation.IRequired;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：碳排数据控制类
 * @Date：Create by 2023-12-01 10:45:08
 */
@Api(tags = "碳排数据")
@RestController
@RequestMapping("/ecp-admin/carbonEmissionData")
public class CarbonEmissionDataController {


    @Resource
    private IEnergyDataService energyDataService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:carbonEmissionData:search")
    public ResultResp<IPage<CarbonEmissionDataResp>> queryPage(@RequestBody @Validated(IQueryPage.class) CarbonEmissionDataQueryReq req) {
        IPage<CarbonEmissionDataResp> page = buildQW(req).joinPage(PageUtils.getPage(req, CarbonEmissionDataResp.class), CarbonEmissionDataResp.class);
        return ResultResp.success(SceneHelper.i().setSceneInfo(page));
    }

    /**
     * 组装查询条件
     *
     * @param req
     * @return
     */
    private static JoinLambdaWrapper<EnergyDataEntity> buildQW(CarbonEmissionDataQueryReq req) {
        Date endTime = req.getEndTime();
        if (Objects.nonNull(endTime)) {
            endTime = DateUtil.endOfDay(endTime);
        }
        return Joins.of(EnergyDataEntity.class)
                .selectAll()
                .leftJoin(MeterDeviceEntity.class, MeterDeviceEntity::getId, EnergyDataEntity::getMeterDeviceId)
                .selectAs(t -> t.addFunAlias(MeterDeviceEntity::getDeviceCode, EnergyDataExtEntity::getDeviceCode)
                        .addFunAlias(MeterDeviceEntity::getDeviceName, EnergyDataExtEntity::getDeviceName)
                        .addFunAlias(MeterDeviceEntity::getReadMeterType, EnergyDataExtEntity::getReadMeterType)
                        .addFunAlias(MeterDeviceEntity::getReadMeterTag, EnergyDataExtEntity::getReadMeterTag))
                .notIn(MeterDeviceEntity::getReadMeterType, IMeterDeviceEnums.ReadMeterType.getZeroCarbonList())
                .eq(StringUtils.isNotEmpty(req.getReadMeterType()), MeterDeviceEntity::getReadMeterType, req.getReadMeterType())
                .end()
                .leftJoin(EnergyConsumptionTypeEntity.class, EnergyConsumptionTypeEntity::getId, EnergyDataEntity::getEnergyTypeId)
                .selectAs(t -> t.addFunAlias(EnergyConsumptionTypeEntity::getEnergyName, EnergyDataExtEntity::getEnergyTypeName)
                        .addFunAlias(EnergyConsumptionTypeEntity::getEnergyUnit, EnergyDataExtEntity::getEnergyTypeUnit))
                .end()
                .leftJoin(ProductTypeEntity.class, ProductTypeEntity::getId, EnergyDataEntity::getProductTypeId)
                .selectAs(t -> t.addFunAlias(ProductTypeEntity::getProductTypeName, CarbonEmissionDataResp::getProductTypeName))
                .end()
                .leftJoin(EnergyCategoryEntity.class, EnergyCategoryEntity::getId, EnergyDataEntity::getEnergyCategory)
                .selectAs(t -> t.addFunAlias(EnergyCategoryEntity::getCategoryName, CarbonEmissionDataResp::getEnergyCategoryName))
                .end()
                .leftJoin(CarbonEmissionRangeEntity.class, CarbonEmissionRangeEntity::getId, EnergyDataEntity::getCalculationRange)
                .selectAs(t -> t.addFunAlias(CarbonEmissionRangeEntity::getRangeName, CarbonEmissionDataResp::getCalculationRangeName))
                .end()
                .leftJoin(SceneProjectEntity.class, SceneProjectEntity::getId, EnergyDataEntity::getSceneProjectId)
                .select(SceneProjectEntity::getProjectName)
                .end()
                .leftJoin(SceneCompanyEntity.class, SceneCompanyEntity::getId, EnergyDataEntity::getSceneCompanyId)
                .select(SceneCompanyEntity::getCompanyName)
                .end()
                .eq(StringUtils.isNotEmpty(req.getSceneProjectId()), EnergyDataEntity::getSceneProjectId, req.getSceneProjectId())
                .eq(StringUtils.isNotEmpty(req.getEnergyTypeId()), EnergyDataEntity::getEnergyTypeId, req.getEnergyTypeId())
                .eq(StringUtils.isNotEmpty(req.getSceneEdificeId()), EnergyDataEntity::getSceneEdificeId, req.getSceneEdificeId())
                .eq(StringUtils.isNotEmpty(req.getSceneFloorId()), EnergyDataEntity::getSceneFloorId, req.getSceneFloorId())
                .eq(StringUtils.isNotEmpty(req.getSceneRoomId()), EnergyDataEntity::getSceneRoomId, req.getSceneRoomId())
                .eq(StringUtils.isNotEmpty(req.getProductTypeId()), EnergyDataEntity::getProductTypeId, req.getProductTypeId())
                .eq(StringUtils.isNotEmpty(req.getStaticsType()), EnergyDataEntity::getStaticsType, req.getStaticsType())
                .in(CollectionUtils.isNotEmpty(req.getIds()), EnergyDataEntity::getId, req.getIds())
                .ge(req.getBeginTime() != null, EnergyDataEntity::getSolidifyDate, req.getBeginTime())
                .le(Objects.nonNull(endTime), EnergyDataEntity::getSolidifyDate, endTime)
                .last(StringUtils.isNotEmpty(req.getSortColumn()), PageUtils.lastOrderBy(req))
                .orderByDesc(StringUtils.isEmpty(req.getSortColumn()), EnergyDataEntity::getSolidifyDate);
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:carbonEmissionData:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(energyDataService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:carbonEmissionData:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(energyDataService.removeBatchByIds(req.getIds(), 1000));
    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:carbonEmissionData:export")
    public void export(@RequestBody @Validated(IExport.class) CarbonEmissionDataQueryReq req, HttpServletResponse response) {
        List<CarbonEmissionDataResp> list = SceneHelper.i().setSceneInfo(buildQW(req).joinList(CarbonEmissionDataResp.class));
        ExcelXSSFUtil.export("CarbonEmissionDataExport", JsonUtil.toJson(list), response);
    }

}
